import request from '@/utils/request';
import { getToken, removeToken, setToken, getSystemId, getPermissions } from '@/utils/utils'
import { buildRouters } from '@/router/buildRoutes';

const state = {
  token: getToken(),
  nickName: '',
  orgName: '',
  avatar: '',
  info: {},
  permissions: '',
  roles: '',
  routesLoaded: false,
  routers: []
}

// 实例化
const user = {
  namespaced: true,
  state,

  mutations: {

    SET_TOKEN (state, token) {
      setToken(token);
      state.token = token;
    },

    SET_PERMISSIONS (state, permissions) {
      state.permissions = permissions;
    },
    
    SET_USER (state, user) {
      state.info = user;

      state.nickName = user.nickName;
      state.orgName = user.orgName;
      state.avatar = user.avatar;
      state.roles = user.roleNames;
    },

    SET_ROUTES_LOADED (state, loaded) {
      state.routesLoaded = loaded;
    },

    SET_ROUTERS (state, routers) {
      state.routers = routers;
    },

    CLEAR_STATE (state) {
      removeToken();
      state.user = {};
      state.token = '';
      state.permissions = '';
      state.roles = '';
      state.nickName = '';
      state.orgName = '';
      state.menus = [];

      localStorage.clear();
      localStorage.removeItem('app-store');
    }
  },

  actions: {

    setToken (context, token) {
      return new Promise((resolve, reject) => {
        context.commit('SET_TOKEN', token);
        resolve();
      })
    },

    setUser (context) {
      return new Promise((resolve, reject) => {
        request.get('/upms/profile/get').then(response => {
          const user = response.data.data;
          context.commit('SET_USER', user)
          resolve(user);
        }).catch(err => {
          reject(err)
        })
      });
    },

    setRouters (context) {
      return new Promise((resolve, reject) => {
        const systemId = getSystemId();
        request.get('/upms/menu/list/my/tree?systemId=' + systemId).then(response => {
          const menus = response.data.data;
          const routers = buildRouters(menus);
          context.commit('SET_ROUTERS', routers);
          const permissions = getPermissions(menus).join(',');
          context.commit('SET_PERMISSIONS', permissions);
          resolve(routers);
        }).catch(err => {
          reject(err)
        })
      });
    },

    setPermissions (context, permissions) {
      return new Promise((resolve, reject) => {
        context.commit('SET_PERMISSIONS', permissions);
        resolve();
      })
    },

    clearState (context) {
      return new Promise((resolve, reject) => {
        context.commit('CLEAR_STATE');
        resolve();
      })
    },
  }
}

export default user